package xyz.labmem.main.error;

import cn.hutool.core.util.ReflectUtil;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.labmem.main.result.ResultUtil;
import xyz.labmem.main.result.ResultValid;
import xyz.labmem.main.result.ResultVo;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lty
 * Created in 11:05 2020-3-5
 */
@ControllerAdvice
public class ExceptionValidHandler {

    private final static boolean debug = true;

    /**
     * RequestBody校验捕获
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    ResultVo MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            List<ResultValid> validMsgs = new ArrayList<>();
            if (debug)
                allErrors.forEach(objectError -> {
                    FieldError fieldError = (FieldError) objectError;
                    try {
                        Object source = ReflectUtil.getFieldValue(fieldError, "source");
                        var been = ReflectUtil.getFieldValue(source, "rootBean").getClass();
                        Field field = been.getDeclaredField(fieldError.getField());
                        ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
                        validMsgs.add(new ResultValid(apiModelProperty.value(), fieldError.getDefaultMessage()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        validMsgs.add(new ResultValid(fieldError.getField(), fieldError.getDefaultMessage()));
                    }
                });
            return ResultUtil.formFailed("表单验证失败", validMsgs);
        } else
            return ResultUtil.formFailed();
    }


}
